<?php

class Auth extends Controller {

    public function __construct() {
        parent::Controller();
        $this->load->model('usermodel', 'user');
    }

    public function index() {
        $this->load->helper('form');
        $data['title'] = '管理员登录';
        $this->load->view('auth/form', $data);
    }

    public function login() {
        
        if ($this->user->isAuthenticated()) {
            $this->session->set_userdata('isAuthenticated', true);
            $this->session->set_userdata('username', $this->input->post('username'));
            redirect(base_url().'/admin.php?c=firm&m=index');
        } else {
            redirect(base_url().'/admin.php?c=auth&m=index');
        }
    }

    public function logout() {
        if ($this->session->userdata('isAuthenticated')) {
            $this->session->set_userdata('isAuthenticated', false);
        }
        redirect(base_url().'/admin.php?c=auth&m=index');
    }

    public function changePassword() {
        if ($this->session->userdata('isAuthenticated')) {
            $this->load->helper('form');
            $this->load->view(base_url().'/admin.php?c=auth&m=changepassword');
        } else {
            redirect(base_url().'/admin.php?c=auth&m=index');
        }
    }

    public function passwordChange() {
        if ($this->session->userdata('isAuthenticated')) {
            $password = $this->input->post('password');
            $passwordconfirm = $this->input->post('passwordconfirm');

            if ($password == $passwordconfirm) {
                $data['password'] = md5($password);
                if ($this->db->update('user', $data, array('username' => $this->session->userdata('username')))) {
                    $this->session->set_flashdata('notice', '密码修改成功！');
                } else {
                    $this->session->set_flashdata('error', '数据库错误！');
                }
            } else {
                $this->session->set_flashdata('error', '密码不一致！');
            }
           $this->load->view(base_url().'/admin.php?c=auth&m=changepassword');
        } else {
           redirect(base_url().'/admin.php?c=auth&m=index');
        }
    }

    /*
    public function create() {
        $this->load->helper('form');
        $data['permissions'] = $this->getPermissions();
        $this->load->view('auth/create', $data);
    }

    private function getPermissions() {
        return array(
            '0' => 'superadmin',
            '1' => 'admin',
            '2' => 'member'
        );
    }
    */

}
